﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using HSDc.RingleFlow.Api.Rule;
using HSDc.RingleFlow.Kernel.Persistence;
using System.Configuration;

namespace HSDc.RingleFlow.Kernel.DBPersit.Util
{
    internal class WFObjectFactory
    {
        internal static Activity NewActivity(object source, string className, object[] args)
        {
            Assembly instance = Assembly.GetAssembly(source.GetType());
            Activity ac = (Activity)instance.CreateInstance(className, false, BindingFlags.Default,
                null, args, null, null);
            return ac;
        }

        internal static IRule NewRule(object source, string className, object[] args)
        {
            if (string.IsNullOrEmpty(className))
                return null;
            Assembly instance = GetObject("kernel/CustomRuleDll");
            IRule rule = (IRule)instance.CreateInstance(className, false, BindingFlags.Default,
                null, args, null, null);
            return rule;
        }

        private static Assembly GetObject(string configName)
        {
            PersistHandler configSection = new PersistHandler();
            string configPath = configSection.GetType().Assembly.CodeBase.Substring(8).Replace("/", "\\");
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
            //string className = (string)config.GetSection(configName).ElementInformation.Properties["className"].Value;
            AssemblyName myAssemblyName = new AssemblyName();
            myAssemblyName.Name = config.GetSection(configName).ElementInformation.Properties["dllName"].Value.ToString();
            myAssemblyName.CodeBase = configSection.GetType().Assembly.CodeBase;
            //myAssemblyName.CodeBase = myAssemblyName.CodeBase.Substring(0, myAssemblyName.CodeBase.LastIndexOf("/")) +"/"+ myAssemblyName.Name + ".DLL";
            Assembly instance = Assembly.Load(myAssemblyName);
            return instance;
        }
    }
}
